package proc

import (
	"bufio"
	"fmt"
	"io"
	"log"
	"os"
	"strings"
)

// ReadFunc 读取方法
type ReadFunc = func(r io.Reader)

// StdIn 正常输入
func (c *Cmd) StdIn(in ...io.Reader) *Cmd {
	if c == nil {
		return c
	}
	if len(in) > 0 {
		c.stdin = in[0]
	} else {
		c.stdin = os.Stdin
	}
	return c
}

// StdOut 正常输出
func (c *Cmd) StdOut(out ...io.Writer) *Cmd {
	if c == nil {
		return c
	}
	if len(out) > 0 {
		c.stdout = out[0]
	} else {
		c.stdout = os.Stdout
	}
	return c
}

// ErrOut 错误输出
func (c *Cmd) ErrOut(out ...io.Writer) *Cmd {
	if c == nil {
		return c
	}
	if len(out) > 0 {
		c.stderr = out[0]
	} else {
		c.stderr = os.Stderr
	}
	return c
}

// ReadOut 读取正常输入
func (c *Cmd) ReadOut(readOut ReadFunc) *Cmd {
	c.readOut = readOut
	return c
}

// ReadErr 读取错误输出
func (c *Cmd) ReadErr(readErr ReadFunc) *Cmd {
	c.readErr = readErr
	return c
}

// ReadByLine 逐行读取
func ReadByLine(read func(line string)) ReadFunc {
	return func(r io.Reader) {
		br := bufio.NewReader(r)
		for {
			line, err := br.ReadString('\n')
			if err != nil {
				if err == io.EOF {
					break
				}
				read(fmt.Sprintf("ERR: %v", err))
				return
			}
			read(strings.TrimSuffix(line, "\n"))
		}
	}
}

// PrintLine 逐行读取并打印
func PrintLine(prefix string) ReadFunc {
	return ReadByLine(func(line string) { log.Printf("[%s] %s", prefix, line) })
}
